package malvados.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import malvados.app.bin.Favorito;
import malvados.app.bin.ListaFavoritos;
import malvados.app.bin.ShakeListener;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class MalvadosActivity extends Activity
{
    private ImageView imgTirinha;
    private ImageView imgTopo;
    //private ImageView btnRandom;
    private ImageView btnFavorito;
    private int IdTirinha = 1593;
    private int idLastCartoon = 0;
    float x1 = 0, x2 = 0, y1 = 0, y2 = 0, dx = 0, dy = 0;
    int defaultX = 15;
    private ProgressDialog dialog;
    private int selectedImageViewX;
    private int selectedImageViewXend;
    public static final Map<String, Drawable> MapaTirinhas = new HashMap<String, Drawable>();
    public static final Map<String, Drawable> MapaTopos = new HashMap<String, Drawable>();
    int random = 0;
    private SensorManager mSensorManager;
    private ShakeListener mSensorListener;
    private final int SLIDE_TOLERANCE = 80;
    private int screenWith =  0;
    private int screenHeight = 0;
    static final int resultIdTirinha = 0;
    public static String RESULTADO = "RESULTADO";
    private boolean isLongPress;
    Favorito favorito = new Favorito();

    public MalvadosActivity() {}

   
    
    @Override
    public void onResume() {
        super.onResume();
        mSensorManager.registerListener(mSensorListener,
        mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_UI);
     }

    @Override
    public void onStop() {
        mSensorManager.unregisterListener(mSensorListener);
        super.onStop();
      }
      
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        imgTirinha = (ImageView) findViewById(R.id.imgTirinha);
        imgTopo = (ImageView) findViewById(R.id.imgTitulo);
        btnFavorito = (ImageView) findViewById(R.id.btnFavorito);
        //btnRandom = (ImageView) findViewById(R.id.btnRandom);
        
        screenWith = getWindowManager().getDefaultDisplay().getWidth();
        screenHeight = getWindowManager().getDefaultDisplay().getHeight();
        

        //shake inicio
        mSensorListener = new ShakeListener();
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener((SensorEventListener) mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_UI);


        mSensorListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
                public void onShake(){
                    if(!dialog.isShowing())
                        carregaImagens(new Random().nextInt(idLastCartoon));
                }
        });

        //shake end
        try {
            this.IdTirinha = getIdLastCartoon();
            this.idLastCartoon = IdTirinha;
        } catch (IOException ex) {
            Logger.getLogger(MalvadosActivity.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        imgTirinha.setOnLongClickListener(new ImageView.OnLongClickListener() {
			
			public boolean onLongClick(View v) {
				if(isLongPress){
					Intent intent = new Intent(MalvadosActivity.this, ZoomView.class);
					intent.putExtra("IdTirinha", IdTirinha);
	            	startActivity(intent);
				}
				return true;
			}
		});

        imgTirinha.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View arg0, MotionEvent arg1) {
                boolean retorno = false;
                String direction = "";
                switch(arg1.getAction()) {
                    case(MotionEvent.ACTION_DOWN):
                        x1 = arg1.getRawX();
                        y1 = arg1.getY();
                        selectedImageViewX = Math.abs((int)arg1.getRawX()-((ImageView)arg0).getLeft());
                        selectedImageViewXend = Math.abs((int)arg1.getRawX()+((ImageView)arg0).getRight());
                        retorno = false;
                        isLongPress = true;
                        break;
                    case(MotionEvent.ACTION_UP):
                        x2 = arg1.getRawX();
                        y2 = arg1.getY();
                        dx = x2-x1;
                        dy = y2-y1;

                        if(Math.abs(dx) > Math.abs(dy)) {
                            if(dx>0)
                                direction = "right";
                            else
                                direction = "left";
                        }
                        if(direction.equals("right")){
                            if(dx>SLIDE_TOLERANCE){
                                carregaImagens(IdTirinha-1);
                            }
                            else{
                                TranslateAnimation anim = new TranslateAnimation((int)arg1.getRawX()-selectedImageViewX,0,0,0);
                                anim.setDuration(250);
                                //anim.setFillAfter(true);
                                imgTirinha.startAnimation(anim);                              
                            }

                        }else if(direction.equals("left")){
                            if((dx<-SLIDE_TOLERANCE)&&(!((IdTirinha+1)>idLastCartoon))){
                                //if(!((IdTirinha+1)>idLastCartoon)){
                                    carregaImagens(IdTirinha+1);
                                //}
                            }else{
                            	TranslateAnimation anim = new TranslateAnimation((int)arg1.getRawX()-selectedImageViewX,0,0,0);
                                anim.setDuration(250);
                                //anim.setFillAfter(true);
                                imgTirinha.startAnimation(anim); 
                            }

                        }
                        RelativeLayout.LayoutParams temp2 = new RelativeLayout.LayoutParams(imgTirinha.getLayoutParams());
                        temp2.setMargins(((screenWith/2)-imgTirinha.getWidth()/2), imgTopo.getHeight()+5, 0, 0);
                        temp2.addRule(RelativeLayout.BELOW, R.id.imgTirinha);
                        imgTirinha.setLayoutParams(temp2);
                        retorno = true;
                        isLongPress = false;
                        break;
                    case (MotionEvent.ACTION_MOVE):
                        RelativeLayout.LayoutParams temp = new RelativeLayout.LayoutParams(imgTirinha.getLayoutParams());
                        temp.setMargins((int)arg1.getRawX()-selectedImageViewX, imgTopo.getHeight()+5, (int)arg1.getRawX()+selectedImageViewXend, 0);
                        temp.addRule(RelativeLayout.BELOW, R.id.imgTirinha);
                        imgTirinha.setLayoutParams(temp);
                        retorno = true;
                        isLongPress = false;
                        break;
                    
                }

                return retorno;
                }
        });


        carregaImagens(idLastCartoon);

//        btnRandom.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View arg0) {
//                carregaImagens(new Random().nextInt(idLastCartoon));
//            }
//        });
        
        btnFavorito.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				final EditText input = new EditText(MalvadosActivity.this);
				
				if(!ListaFavoritos.verificaFavorito(new Favorito(String.valueOf(IdTirinha),""))){
					new AlertDialog.Builder(MalvadosActivity.this)
				    .setTitle("Adicionar Favoritos")
				    .setMessage("Descricao")
				    .setView(input)
				    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				        public void onClick(DialogInterface dialog, int whichButton) {
				            favorito.setDescricao(input.getText().toString()); 
				            favorito.setCodigoTirinha(String.valueOf(IdTirinha));
				            try {
								ListaFavoritos.inserir(favorito);
								btnFavorito.setImageDrawable(getResources().getDrawable(R.drawable.favorito) );
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				        }
				    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				        public void onClick(DialogInterface dialog, int whichButton) {
				            // Do nothing.
				        }
				    }).show();
				}else{
					new AlertDialog.Builder(MalvadosActivity.this)
				    .setTitle("Remover dos Favoritos")
				    .setMessage("Deseja Mesmo Remover?")
				    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				        public void onClick(DialogInterface dialog, int whichButton) {
				            favorito.setDescricao(input.getText().toString()); 
				            favorito.setCodigoTirinha(String.valueOf(IdTirinha));
				            try {
								ListaFavoritos.remover(favorito);
								btnFavorito.setImageDrawable(getResources().getDrawable(R.drawable.naofavorito) );
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
				        }
				    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				        public void onClick(DialogInterface dialog, int whichButton) {
				            // Do nothing.
				        }
				    }).show();
				}
				
				
			}
		});
        
        

        imgTopo.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                carregaImagens(idLastCartoon);
            }
        });
    }

    public void carregaImagens(int Id){
        try {
            this.IdTirinha = Id;
            dialog = ProgressDialog.show(MalvadosActivity.this, "","Carregando. Aguarde...", true);
            new carregaImagens().execute(this.imgTirinha, this.imgTopo);
            if(ListaFavoritos.verificaFavorito(new Favorito(String.valueOf(IdTirinha),"")))
            	btnFavorito.setImageDrawable(getResources().getDrawable(R.drawable.favorito) );
            else
            	btnFavorito.setImageDrawable(getResources().getDrawable(R.drawable.naofavorito) );
            	
            //new carregaImagensMarginais().cancel(true);
            //new carregaImagensMarginais().execute();
            
        } catch (Exception ex) {
            //Logger.getLogger(MalvadosActivity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Drawable getTirinha(int Id){
        Drawable retorno = null;
        try {
            if(MapaTirinhas.containsKey(String.valueOf(Id))){
                retorno = MapaTirinhas.get(String.valueOf(Id));
            }else{
                retorno = getImage("http://www.malvados.com.br/tirinha" + Id + ".jpg");
                MapaTirinhas.put(String.valueOf(Id), retorno);
            }
            return retorno;
        } catch (Exception ex) {
            try {
                retorno = getImage("http://www.malvados.com.br/tirinha" + Id + ".gif");
                MapaTirinhas.put(String.valueOf(Id), retorno);
                return retorno;
            } catch (Exception ex1) {
            	//imgTirinha.setImageDrawable(getResources().getDrawable(R.drawable.tirinha) );
                //Logger.getLogger(MalvadosActivity.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        return getResources().getDrawable(R.drawable.tirinha);
    }

    public Drawable getTopo(int Id) {
        Drawable retorno = null;
        try {
            if(MapaTopos.containsKey(String.valueOf(Id))){
                retorno = MapaTopos.get(String.valueOf(Id));
            }else{
                retorno = getImage("http://www.malvados.com.br/logo" + Id + ".gif");
                MapaTopos.put(String.valueOf(Id), retorno);
            }
            return retorno;
        } catch (Exception ex) {
            //imgTopo.setImageDrawable(getResources().getDrawable(R.drawable.logo) );
        }
        return getResources().getDrawable(R.drawable.logo);
    }

    public int getIdLastCartoon() throws IOException{

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://www.malvados.com.br");
        HttpResponse response = client.execute(request);

        String html = "";
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while((line = reader.readLine()) != null)
        {
            str.append(line);
        }
        in.close();
        html = str.toString().substring(str.toString().indexOf("mainFrame")+21,str.toString().indexOf("</frameset>")-9);

        return Integer.valueOf(html);
    }

    public Drawable getImage(String caminho) throws IOException  {
        
			URL url;
			url = new URL(caminho);
			InputStream is;
			is = (InputStream) getObjeto(url);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		   
    }
    
    private Object getObjeto(URL url) throws IOException {
			Object content;
			content = url.getContent();
			return content;	
    }

    class carregaImagensMarginais extends AsyncTask<Object, Object, Object> {
        @Override
        protected Object doInBackground(Object... params) {

            getTirinha(IdTirinha-1);
            getTopo(IdTirinha-1);

            if(!(IdTirinha >= idLastCartoon)){
                getTopo(IdTirinha+1);
                getTirinha(IdTirinha+1);
            }
        
            return true; 
        }

        @Override
        protected void onPostExecute(Object result) {
            
        }
    }

    class carregaImagens extends AsyncTask<ImageView, Void, Drawable>{

        ImageView tirinha = null;
        ImageView topo = null;
        @Override
        protected Drawable doInBackground(ImageView... imageView){
            this.tirinha = imageView[0];
            this.topo = imageView[1];
            getTopo(IdTirinha);
            return getTirinha(IdTirinha);
        }

        @Override
        protected void onPostExecute(Drawable result) {
            //tirinha.setImageDrawable(getResources().getDrawable(R.drawable.tirinha));
            //topo.setImageDrawable(getResources().getDrawable(R.drawable.logo));
        	tirinha.setImageDrawable(result);
            topo.setImageDrawable(getTopo(IdTirinha));
            dialog.dismiss();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.share:
                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            	Uri tirinha = Uri.parse(getImageToShare(getTirinha(IdTirinha)));
                sharingIntent.setType("image/jpeg");
                sharingIntent.putExtra(Intent.EXTRA_STREAM, tirinha);
            //	sharingIntent.setType("text/plain");
			
			//try {
			//	sharingIntent.putExtra(Intent.EXTRA_TEXT, Shortener.encurtarURL("http://www.malvados.com.br/index"+IdTirinha+".html"));
			//} catch (Exception e) {
			//	//  Auto-generated catch block
			//	e.printStackTrace();
			//}

                startActivity(Intent.createChooser(sharingIntent, "Compartilhar com:"));
                return true;
            case R.id.favoritos:
            	Intent intent = new Intent(MalvadosActivity.this, ViewFavoritos.class);
            	startActivityForResult(intent, resultIdTirinha);
                //finish();
            	return true;
            case R.id.exit:
                super.finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public String getImageToShare(Drawable tirinha){
        return  Images.Media.insertImage(getContentResolver(), ((BitmapDrawable)tirinha).getBitmap(), "title", null);
    }
    
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) {     
       if(resultCode == 1){
    	   carregaImagens(Integer.valueOf(data.getStringExtra("IdTirinha")));
       }
       super.onActivityResult(requestCode, resultCode, data);
    }
    
}

